<?php

class Default_Model_Question extends Zend_Db_Table{
	
	protected $_name="tblquestion";
	protected $_primary="id";
	protected $db;
	public function __construct(){
		parent::__construct();
		$this->db=Zend_Registry::get('connectDb');
	}
	// Tổng số câu hỏi
	public function count(){
		$select = $this->db->select()->from('tblquestion AS q',array('COUNT(q.id) AS totalItem'));
		$result=	$this->db->fetchOne($select);
		return $result;
	}
	
	/* Lấy nhiều câu hỏi ra với các option
	 * 
	 */
	public function getItems($param=NULL, $option=NULL){
		$select= $this->db->select()
					->from('tblquestion AS q');
		if($option['task']=='question-view'){
			$select->joinLeft('tbluser AS u','u.id=q.id_user',array('name','url_avatar'))
			->where('q.id='.$param['id']);
			return $this->db->fetchRow($select);
		}
		if($option['task']=='question-list'){	
			$select->joinLeft('tbluser AS u','u.id=q.id_user',array('name','url_avatar'));					
			return $this->db->fetchAll($select);
		}
	
		if($option['filter']=='tag'){
			$select->joinLeft('tbltag AS t','t.id='.$param['id_tag'],array('t.*'))
					->joinLeft('tbluser AS u','u.id=q.id_user',array('name','url_avatar'));
			return $this->db->fetchAll($select);	
		}
		if($option['filter']=='no-answer'){
			$select->joinLeft('tblanswer AS a','a.id_question!=q.id',array('t.*'))
					->joinLeft('tbluser AS u','u.id=q.id_user',array('name','url_avatar'));
			return $this->db->fecthAll($select);	
		}
		if($option['filter']=='new-answer'){
			
		}
		if($option['filter']=='hot-question'){
			
		}
	
				
	}
	//Thêm câu hỏi
	public function saveItem($param=NULL,$option=NULL){
		if($option['do']=="add"){
			$row = $this->fetchNew();
			$row->question=$param['question'];
			$row->title=$param['title'];
			$row->id_user=$param['id_user'];
			$row->time=date("Y-m-d 00-00-00");
			$row->tag=$param['tag'];
			$row->id_tag=$param['id_tag'];
			$row->status=$param['status'];
			$row->count_view=$param['count_view'];
			$row->count_answer=$param['count_asnwer'];
			$row->mod_status=$param['mod_status'];
			$row->img_url=$param['img_url'];
			$row->save();
		}
		if($option['do']=="edit"){
			$row =$this->fetchRow('id=?',$param['id']);
			$row->question=$param['question'];
			$row->title=$param['title'];
			$row->id_user=$param['id_user'];
			$row->time=date("Y-m-d 00-00-00");
			$row->tag=$param['tag'];
			$row->id_tag=$param['id_tag'];
			$row->status=$param['status'];
			$row->count_view=$param['count_view'];
			$row->count_answer=$param['count_asnwer'];
			$row->mod_status=$param['count_asnwer'];
			$row->img_url=$param['img_url'];
			$row->save();
		}
	}
	public function deleteItem($param=NULL,$option=NULL){
		$this->delete('id='.$param['id']);
		if($option['task']=='mutil-del'){
			//
		}
	}
	public function changeStatus($param=NUll){
		$this->update(array('status'=>$param['status']),'id='.$param['id']);
	}
}